<template>
  <div class="map-container">
    <div id="map" class="map"></div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <button @click="addRandomPoints(50)">
        添加随机点({{ points.length }})
      </button>
      <button @click="clearPoints">
        清除所有点
      </button>
      <div class="distance-control">
        <span>聚合距离: {{ distance }}px</span>
        <el-slider v-model="distance" :min="20" :max="200" @change="updateCluster">
        </el-slider>
      </div>
    </div>
  </div>
</template>

<script>
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
import 'leaflet.markercluster/dist/MarkerCluster.css'
import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import 'leaflet.markercluster'

export default {
  name: 'ClusterDemo',

  data() {
    return {
      map: null,
      points: [],
      markerClusterGroup: null,
      distance: 40, // 聚合距离
      markerIcon: null, // 标记点图标
      bounds: { // 随机点的范围(新疆范围)
        minLat: 34.4,
        maxLat: 49.2,
        minLng: 73.5,
        maxLng: 96.4
      }
    }
  },

  mounted() {
    this.initMap()
    this.initMarkerIcon()
  },

  methods: {
    initMap() {
      // 初始化地图
      this.map = L.map('map', {
        center: [43.792818, 87.617733], // 乌鲁木齐市中心坐标
        zoom: 6,
        zoomControl: true
      })

      // 添加高德底图
      L.tileLayer('https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
        subdomains: ["1", "2", "3", "4"],
        attribution: '&copy; 高德地图'
      }).addTo(this.map)

      // 初始化聚合图层
      this.initClusterLayer()
    },

    initClusterLayer() {
      // 创建聚合图层
      this.markerClusterGroup = L.markerClusterGroup({
        maxClusterRadius: this.distance,
        spiderfyOnMaxZoom: true,
        showCoverageOnHover: true,
        zoomToBoundsOnClick: true,

        // 自定义聚合点的图标样式
        iconCreateFunction: (cluster) => {
          const count = cluster.getChildCount()
          let size = 'small'

          if (count > 50) size = 'large'
          else if (count > 20) size = 'medium'

          return L.divIcon({
            html: `<div><span>${count}</span></div>`,
            className: `custom-cluster-icon ${size}`,
            iconSize: L.point(40, 40)
          })
        }
      })

      // 添加到地图
      this.map.addLayer(this.markerClusterGroup)
    },

    initMarkerIcon() {
      // 创建自定义图标
      this.markerIcon = L.icon({
        iconUrl: '/images/markers/PP_CJ.png', // 图标路径
        iconSize: [32, 32], // 图标大小
        iconAnchor: [16, 32], // 图标锚点(相对于图标左上角的偏移)
        popupAnchor: [0, -34] // 弹窗锚点(相对于iconAnchor的偏移)
      })
    },

    // 添加随机点
    addRandomPoints(count) {
      const { minLat, maxLat, minLng, maxLng } = this.bounds

      for (let i = 0; i < count; i++) {
        const lat = minLat + Math.random() * (maxLat - minLat)
        const lng = minLng + Math.random() * (maxLng - minLng)

        const point = {
          id: this.points.length + 1,
          lat,
          lng,
          name: `点位 ${this.points.length + 1}`
        }

        this.points.push(point)

        // 创建带文字标签的标记
        const marker = L.marker([lat, lng], {
          icon: L.divIcon({
            className: 'marker-label',
            html: `
              <div class="marker-content">
                <span class="marker-text">${point.name}</span>
                <img src="/images/markers/cjyl.gif" class="marker-icon" />
              </div>
            `,
            iconSize: [32, 32],
            iconAnchor: [16, 32]
          })
        })

        // 添加弹窗
        marker.bindPopup(`
          <div class="custom-popup">
            <h3>${point.name}</h3>
            <p>经度: ${lng.toFixed(4)}</p>
            <p>纬度: ${lat.toFixed(4)}</p>
          </div>
        `,
          {
            className: 'custom-popup-wrapper',
            closeButton: false,
            offset: [0, -10],
            openOnClick: false,
            autoClose: true,
            closeOnClick: false
          }).on('mouseover', function (e) {
            this.openPopup();
          })
          .on('mouseout', function (e) {
            this.closePopup();
          })

        this.markerClusterGroup.addLayer(marker)
      }
    },

    // 清除所有点
    clearPoints() {
      this.markerClusterGroup.clearLayers()
      this.points = []
    },

    // 更新聚合距离
    updateCluster() {
      this.map.removeLayer(this.markerClusterGroup)
      this.initClusterLayer()

      // 重新添加所有点
      this.points.forEach(point => {
        const marker = L.marker([point.lat, point.lng], {
          icon: L.divIcon({
            className: 'marker-label',
            html: `
              <div class="marker-content">
                <img src="/images/markers/PP_CJ.png" class="marker-icon" />
                <span class="marker-text">${point.name}</span>
              </div>
            `,
            iconSize: [32, 32],
            iconAnchor: [16, 32]
          })
        })

        marker.bindPopup(`
          <div class="custom-popup">
            <h3>${point.name}</h3>
            <p>经度: ${point.lng.toFixed(4)}</p>
            <p>纬度: ${point.lat.toFixed(4)}</p>
          </div>
        `)

        this.markerClusterGroup.addLayer(marker)
      })
    }
  },

  beforeDestroy() {
    if (this.map) {
      this.map.remove()
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.toolbar {
  position: absolute;
  top: 10px;
  left: 10px;
  background: white;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 200px;

  button {
    margin: 0 5px;
    padding: 8px 15px;
    border: 1px solid #dcdfe6;
    background: white;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    font-size: 14px;
    color: #606266;

    &:hover {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
}

.distance-control {
  margin-top: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;

  span {
    display: block;
    margin-bottom: 8px;
    color: #606266;
    font-size: 14px;
  }
}

/* 自定义聚合点样式 */
:deep(.custom-cluster-icon) {
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  border: 2px solid white;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.1);
  }

  &.small {
    background: #67c23a;
  }

  &.medium {
    background: #e6a23c;
  }

  &.large {
    background: #f56c6c;
  }

  div {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
  }
}

/* 自定义弹窗样式 */
:deep(.custom-popup) {
  padding: 10px;

  h3 {
    margin: 0 0 8px 0;
    font-size: 16px;
    color: #303133;
  }

  p {
    margin: 5px 0;
    font-size: 14px;
    color: #606266;
  }
}

/* 标记文本样式 */
::v-deep .marker-label {
  background: none;
  border: none;
  position: relative;
}

::v-deep .marker-content {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

::v-deep .marker-icon {
  width: 22px;
  height: 22px;
  margin-bottom: 4px;
}

::v-deep .marker-text {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 2px;
  font-size: 12px;
  color: #fff;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  white-space: nowrap;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 悬浮效果 */
::v-deep .marker-content:hover .marker-text {
  background: rgba(0, 0, 0, 0.8);
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style> 